package com.csdj.t309.geamtest.config;

import com.csdj.t309.geamtest.common.CacheConstant;
import com.csdj.t309.geamtest.common.WebResult;
import com.csdj.t309.geamtest.common.WebResultMsgCode;
import com.csdj.t309.geamtest.service.RedisService;
import com.csdj.t309.geamtest.service.UserService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 23793
 */
public class LoginInterceptor implements HandlerInterceptor {
    private RedisService redisService;

    public LoginInterceptor(RedisService redisService){
        this.redisService = redisService;
    }


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uid = request.getHeader(CacheConstant.HEADER_UID);
        if(StringUtils.hasText(uid)){
            String token = request.getHeader(CacheConstant.HEADER_TOKEN);
            if(StringUtils.hasText(token)){
                String cacheToken = redisService.getString(CacheConstant.TOKEN_PREFIX+uid);
                if(token.equals(cacheToken)){
                    return true;
                }
            }
        }
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        WebResult noLogin = new WebResult(WebResultMsgCode.USER_NO_LOGIN);
        ObjectMapper objectMapper = new ObjectMapper();
        response.getWriter().write(objectMapper.writeValueAsString(noLogin));
        response.flushBuffer();
        return false;
    }
}